'''
-*-  coding:  utf-8  -*-
Time    : 15:14
Auther  :罗老师
File    :power.py
'''
import time
import pyvisa


# 连接电源
def connect_power_by_usb(devices_id="10A0"):
    rm = pyvisa.ResourceManager()
    # 获取当前的所有的可用设备，返回一个列表
    resource_list = rm.list_resources()
    target_resource = None
    if resource_list:
        for res in resource_list:
            if "USB" in res:
                if devices_id in res:
                    target_resource = devices_id
                    break
        if not target_resource:
            print(f"{devices_id}设备未找到")
    else:
        print("未找到可以使用的USB控制程序")

    try:
        # 连接设备
        instrument = rm.open_resource(target_resource)
        instrument.timeout = 3000
        print(f"已连接设备：{devices_id}")
        return instrument
    except pyvisa.errors.VisaIOError as e:
        print(f"连接失败：{e}")
        return


def power_state(instrument, state):
    if (state == "ON") or (state == "on"):
        cmd = "OUTPut ON"
    elif (state == "OFF") or (state == "off"):
        cmd = "OUTPut OFF"
    else:
        print("输入异常")
        return
    instrument.write(cmd)


def read_power_single(instrumengt):
    result = {}
    result["voltage"] = float(instrumengt.query("MEASure:VOLTage?"))
    result["current"] = float(instrumengt.query("MEASure:CURRent?"))
    return result


def set_power_paramter(instrument, voltage=14.5, current_limit=3.0):
    # 这只电源限制电流，和电源电压
    instrument.write(f"VOLTage {voltage}")
    instrument.write(f"CURRent {current_limit}")


def main():
    # 首席按读取连接的设备信息，串口状态 # 连接程控电源
    ps = connect_power_by_usb()
    if ps:
        return
    # 配置电源参数
    try:
        set_power_paramter(ps)
        power_state(ps, "ON")
        time.sleep(2)
        # 读取电源数据
        res = read_power_single(ps)
        print(f"当前电压是：{res['voltage']}")
        print(f"当前电流：{res['current']}")
        power_state(ps, "OFF")

    # 执行电源上电

    # 实时读取电源参数
    except Exception as e:
        print(f"操作异常{e}")
    finally:
        ps.close()


if __name__ == "__main__":
    main()
